package com.huajin.gateway.netcard.service;

import com.huajin.gateway.netcard.domain.NetCard;
import com.huajin.gateway.util.Constant;
import com.huajin.gateway.util.RegexUtil;
import com.huajin.gateway.util.SystemCommand;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


@Service
public class NetCardService {

    public List<NetCard> listNetCard() {
        List<NetCard> netCards = new ArrayList<>();
        String content = SystemCommand.runCommand("ip link show");

        List<String> netCardsName = RegexUtil.getRegexResultCardName(Constant.CARDNAME, content);
        for (String s : netCardsName) {
            netCards.add(listNetCardByName(s));
        }
        return netCards;
    }

    public NetCard listNetCardByName(String name) {
        NetCard netCard = new NetCard();
        netCard.setName(name);
        String content = SystemCommand.runCommand("ip add show " + name);

        //ip
        netCard.setIp(RegexUtil.getRegexResult1(Constant.IP, content));

        //mac
        netCard.setMac(RegexUtil.getRegexResult1(Constant.MAC, content));

        //mask
        netCard.setMask(RegexUtil.getRegexResult1(Constant.MASK, content));

        //status
        netCard.setStatus(RegexUtil.getRegexResult2(Constant.STATUS, content));

        //mtu
        netCard.setMtu(RegexUtil.getRegexResult1(Constant.MTU, content));

        //ip request means
        netCard.setDynamic(RegexUtil.getRegexResult2(Constant.DYNAMIC, content));

        return netCard;
    }

    public void changeStatusOnbyName(String name) {
        String command = "ip link set " + name + " up";
        SystemCommand.runCommand(command);
    }

    public void changeStatusOffbyName(String name) {
        String command = "ip link set " + name + " down";
        SystemCommand.runCommand(command);
    }

    public void delIpbyName(String ip, String name) {
        String delCommand = "ip addr del " + ip + "/24 " + " dev " + name;
        SystemCommand.runCommand(delCommand);
    }

    public void setDynamicOn(String name) {
        String dynamicCommand = "ip link set dev " + name + " dynamic on ";
        SystemCommand.runCommand(dynamicCommand);
    }

    public void addIpbyName(String ip, String name) {
        String addCommand = "ip addr add " + ip + "/24 " + " dev " + name;
        SystemCommand.runCommand(addCommand);
    }

    public void setDynamicOff(String name) {
        String dynamicCommand = "ip link set dev " + name + " dynamic off ";
        SystemCommand.runCommand(dynamicCommand);
    }

    public void setMtubyName(String name, String mtu) {
        String mutCommand = "ip link set dev " + name + " mtu " + mtu;
        SystemCommand.runCommand(mutCommand);
    }
}

